<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item  v-if="organizationType === 4" label="税源地" prop="initiatorCompanyName">
        <el-input
          v-model="queryParams.initiatorCompanyName"
          placeholder="请输入税源地名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!--      <el-form-item label="任务编码" v-if="organizationType === 3" prop="taskNo">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.taskNo"-->
      <!--          placeholder="请输入任务编码"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->


      <!--      <el-form-item label="任务名称" v-if="organizationType === 3" prop="taskId">-->
      <!--        <el-select-->
      <!--          v-model="queryParams.taskId"-->
      <!--          filterable-->
      <!--          remote-->
      <!--          clearable-->
      <!--          reserve-keyword-->
      <!--          placeholder="请输入任务名称"-->
      <!--          :remote-method="handleTaskRemote"-->
      <!--          :loading="taskLoading"-->
      <!--        >-->
      <!--          <el-option-->
      <!--            v-for="item in taskOptions"-->
      <!--            :key="item.id"-->
      <!--            :label="item.taskName"-->
      <!--            :value="item.id"-->
      <!--          >-->
      <!--          </el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->

      <el-form-item label="接收方" v-if="organizationType === 3" prop="nickName">
        <el-input
          v-model="queryParams['initiatorUser.nickName']"
          placeholder="请输入接收方"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开票状态" prop="status">
        <el-select v-model="queryParams.status" clearable>
          <el-option :value="0" label="待开票"></el-option>
          <el-option :value="1" label="待验收"></el-option>
          <el-option :value="2" label="完成"></el-option>
          <el-option :value="3" label="驳回"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="发票类型" prop="invoiceType">
        <el-select v-model="queryParams.invoiceType">
          <el-option :value="2" label="普票"></el-option>
          <el-option :value="1" label="专票"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发票类目" prop="invoiceCatagory">
        <el-input
          v-model="queryParams.invoiceCatagory"
          placeholder="请输入发票类目"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="invoiceList">
      <!--      <template v-if="organizationType === 3">-->
      <!--        <el-table-column label="任务编码" align="center" prop="taskName" min-width="180">-->
      <!--          <template slot-scope="{ row }">-->
      <!--            <el-button type="text" size="mini" >{{ row.taskNo }}</el-button>-->
      <!--          </template>-->
      <!--        </el-table-column>-->
      <!--        <el-table-column label="任务名称" align="center" prop="taskName" min-width="200">-->
      <!--          <template slot-scope="{ row }">-->
      <!--            <el-button type="text" size="mini" >{{ row.taskName }}</el-button>-->
      <!--          </template>-->
      <!--        </el-table-column>-->
      <!--      </template>-->
      <el-table-column label="发起方" align="center" prop="receiverCompanyName" min-width="220">
        <template slot-scope="{ row }">
          {{row.receiverCompanyName}}
        </template>
      </el-table-column>
      <el-table-column label="接收方" align="center" prop="initiatorCompanyName" min-width="220">
        <template slot-scope="{ row }">
          {{row.initiatorCompanyName}}
        </template>
      </el-table-column>
      <el-table-column label="税额" align="center" prop="taxAmount" show-overflow-tooltip min-width="120"/>
      <el-table-column label="不含税金额" align="center" prop="taskAmount" show-overflow-tooltip min-width="120"/>
      <el-table-column label="价税合计" align="center" prop="invoiceAmount" show-overflow-tooltip min-width="120"/>
      <el-table-column label="发票类型" align="center" prop="invoiceType" width="120">
        <template slot-scope="{ row }">
          {{row.invoiceType===1?'专票':row.invoiceType===2?'普票':''}}
        </template>
      </el-table-column>
      <el-table-column label="发票类目" align="center" prop="invoiceCatagory" min-width="200" />
      <el-table-column label="发票文件" align="center" prop="invoiceFile" width="100">
        <template slot-scope="{ row }">
          <el-link :href="baseUrl+row.invoiceFile" v-if="row.invoiceFile" :underline="false" target="_blank">
            <el-button type="text" size="mini">查看发票</el-button>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template slot-scope="{ row }">
          <el-tag style="cursor: pointer" type="warning" v-if="row.status === 0">开票中</el-tag>
          <el-tag style="cursor: pointer" type="success" v-else-if="row.status === 1">待验收</el-tag>
          <el-tag style="cursor: pointer" v-else-if="row.status === 2">完成</el-tag>
          <el-popover
            placement="bottom"
            title=""
            width="200"
            trigger="click"
            :content="row.reason">
            <el-tag slot="reference" v-if="row.status === 3" style="cursor: pointer" type="danger">驳回</el-tag>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="createTime" width="180" />
      <el-table-column label="开票时间" align="center" prop="invoiceTime" width="180" />
      <el-table-column label="操作" fixed="right" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-hasPermi="['invoice:invoice:toExamine']"
            v-if="scope.row.status === 1"
            @click="handleDetail(scope.row)"
          >验收</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status !== 1"
            @click="handleDetail(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="开票任务" :visible.sync="detailOpen" width="800px" append-to-body>
      <el-table v-loading="loading" :data="invoiceTaskList">
        <el-table-column label="任务名称" align="center" prop="task.taskName" min-width="180"/>
        <el-table-column label="打款金额" v-if="organizationType === 4" align="center" prop="payslip.successAmount">
          <template slot-scope="{ row }">
            <span v-if="row.payslip">
              {{row.payslip.successAmount +row.payslip.successMerchantAmount}}
            </span>
            <span v-else>{{row.invoice.invoiceAmount}}</span>
          </template>
        </el-table-column>
        <el-table-column label="发票类型" align="center" prop="invoice.invoiceType" width="120">
          <template slot-scope="{ row }">
            {{row.invoice.invoiceType===1?'专票':row.invoice.invoiceType===2?'普票':''}}
          </template>
        </el-table-column>
        <el-table-column label="发票类目" align="center" prop="invoice.invoiceCatagory" min-width="180"/>
        <el-table-column label="发票文件" align="center" prop="invoice.invoiceFile" min-width="120">
          <template slot-scope="{ row }">
            <el-link :href="baseUrl+row.invoice.invoiceFile" v-if="row.invoice.invoiceFile" :underline="false" target="_blank">
              <el-button type="text" size="mini">查看发票</el-button>
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="开票时间" align="center" prop="invoice.invoiceTime" width="180" />
      </el-table>
      <pagination
        v-show="invoiceTaskTotal>0"
        :total="invoiceTaskTotal"
        :page.sync="invoiceTaskQuery.pageNum"
        :limit.sync="invoiceTaskQuery.pageSize"
        @pagination="handleDetail"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">取 消</el-button>
      </div>
    </el-dialog>


    <el-drawer :wrapperClosable="false" :close-on-press-escape="false" destroy-on-close title="发票详情" :visible.sync="invoiceOpen" size="70%" append-to-body>
      <el-descriptions title="" border>
        <el-descriptions-item label="税额/元">{{ formattedTotal(form.taxAmount) }}</el-descriptions-item>
        <el-descriptions-item label="不含税金额/元">{{ formattedTotal(form.taskAmount) }}</el-descriptions-item>
        <el-descriptions-item label="价税合计/元">{{ formattedTotal(form.invoiceAmount) }}</el-descriptions-item>
        <el-descriptions-item label="接收方" v-if="organizationType === 4">{{ form.initiatorCompanyName }}</el-descriptions-item>
        <el-descriptions-item label="开票类目">{{ form.invoiceCatagory }}</el-descriptions-item>
        <el-descriptions-item label="发票">
          <el-link :href="baseUrl+form.invoiceFile" v-if="form.invoiceFile" :underline="false" target="_blank">
            <el-button type="text" size="mini">查看发票</el-button>
          </el-link>
        </el-descriptions-item>

      </el-descriptions>
      <el-form :model="invoiceTaskQuery" ref="queryFormListInvoiceTask" class="invoiceTaskQueryClass" size="small" :inline="true" label-width="68px">
        <el-form-item label="任务" prop="taskId">
          <el-select
            v-model="invoiceTaskQuery.taskId"
            filterable
            remote
            clearable
            reserve-keyword
            placeholder="请输入任务名称"
            :remote-method="handleTaskRemote"
            :loading="taskLoading"
          >
            <el-option
              v-for="item in taskOptions"
              :key="item.id"
              :label="item.taskName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getListInvoiceTask">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryListInvoiceTask">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="invoiceTaskList">
        <el-table-column label="任务编码" align="center" prop="task.taskNo" min-width="180"/>
        <el-table-column label="任务名称" align="center" prop="task.taskName" min-width="180"/>
        <el-table-column label="打款金额" v-if="organizationType === 4" align="center" prop="payslip.successAmount">
          <template slot-scope="{ row }">
            <span v-if="row.payslip">
              {{row.payslip.successAmount +row.payslip.successMerchantAmount}}
            </span>
            <span v-else>{{row.invoice.invoiceAmount}}</span>
          </template>
        </el-table-column>
        <el-table-column label="发票类型" align="center" prop="invoice.invoiceType" width="120">
          <template slot-scope="{ row }">
            {{row.invoice.invoiceType===1?'专票':row.invoice.invoiceType===2?'普票':''}}
          </template>
        </el-table-column>
        <el-table-column label="发票类目" align="center" prop="invoice.invoiceCatagory" min-width="180"/>
        <el-table-column label="开票时间" align="center" prop="invoice.invoiceTime" width="180" />
      </el-table>
      <pagination
        v-show="invoiceTaskTotal>0"
        :total="invoiceTaskTotal"
        :page.sync="invoiceTaskQuery.pageNum"
        :limit.sync="invoiceTaskQuery.pageSize"
        @pagination="getListInvoiceTask"
      />

      <div class="dialog-footer" v-if="form.status === 1">
        <el-button :loading="invoiceLoading" type="primary" @click="handleCheckAndAccept(2)">立即验收</el-button>
        <el-button :loading="invoiceLoading" @click="toExamineOpen = true">驳 回</el-button>
      </div>
    </el-drawer>

    <el-drawer :wrapperClosable="false" :close-on-press-escape="false" destroy-on-close title="任务详情" :visible.sync="detailOpen" size="80%" append-to-body>
      <!--      <taskDetail :id="taskId"></taskDetail>-->
    </el-drawer>

    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="提示" :visible.sync="toExamineOpen" width="450px"  append-to-body>
      <el-input
        type="textarea"
        :autosize="{ minRows: 2, maxRows: 4}"
        placeholder="请输入驳回内容"
        v-model="form.reason">
      </el-input>
      <div slot="footer" class="dialog-footer" >
        <el-button :loading="invoiceLoading" type="primary" @click="handleCheckAndAccept(3)">立即验收</el-button>
        <el-button :loading="invoiceLoading" @click="toExamineOpen = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import store from '@/store'
import {toExamine, listInvoiceTaskList} from '@/api/invoice/invoice'
import { listInvoiceTask } from '@/api/invoice/invoiceTask'

import { listTaxMarket } from '@/api/tax/taxMarket'
import { listTask } from '@/api/system/task'

export default {
  name: "InvoiceTask",
  // components: { taskDetail },
  props:{
    type:{
      type:Number,
      default:null,
    },
    detailPayslipData:{
      type:Object,
      default:null,
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      detailOpen:false,
      tslLoading:false,
      agentOptions:[],
      invoiceOpen:false,
      toExamineOpen:false,
      invoiceLoading:false,
      agentLoading:false,
      detailTaskOpen:false,
      merchantLoading:false,
      detailTaskLoading:false,
      taskLoading:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 开票记录表格数据
      invoiceList: [],
      tslOptions:[],
      merchantOptions:[],
      taskOptions:[],
      baseUrl: process.env.VUE_APP_BASE_API,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tslId:null,
        status:null,
        taskId: null,
        taskNo:null,
        type:1,
        payslipId: null,
        initiatorUserId: null,
        receiverUserId: null,
        invoiceAmount: null,
        invoiceType: null,
        invoiceCatagory: null,
        invoiceFile: null,
        invoiceTime: null,
        organizationType:null,
        initiatorCompanyName:"",
        "initiatorUser.nickName":null
      },
      invoiceTaskQuery:{
        pageNum: 1,
        pageSize: 10,
        invoiceId:null,
      },
      form:{
        tsl:{}
      },
      taskId:null,
      invoiceTaskTotal:0,
      invoiceTaskList:[],
      organizationType: store.getters.organizationType,
    };
  },
  created() {
    // this.getList();
  },
  methods: {
    /** 查询开票记录列表 */
    getList() {
      this.loading = true;
      listInvoiceTaskList(this.queryParams).then(response => {
        this.invoiceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams['initiatorUser.nickName'] = null
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleDetail(row){
      this.invoiceOpen = true
      if (row.id){
        this.invoiceTaskQuery.invoiceId = row.id
      }
      this.form = { ...row }
      this.getListInvoiceTask();
    },

    getListInvoiceTask(){
      listInvoiceTask(this.invoiceTaskQuery).then(res=>{
        this.invoiceTaskList = res.rows
        this.invoiceTaskTotal = res.total
      })
    },

    resetQueryListInvoiceTask() {
      this.invoiceTaskQuery.pageNum = 1;
      this.resetForm("queryFormListInvoiceTask");
      this.getListInvoiceTask();
    },


    handleTslRemote(query){
      if (query !== '') {
        this.tslLoading = true;
        if (this.organizationType === 4 || this.organizationType === 2) {
          listTaxMarket({ auditStatus: 2, cooperateAuditStatus: 2, name: query }).then(response => {
            this.tslOptions = response.rows;
            this.tslLoading = false;
          }).catch(() => {
            this.tslLoading = false
          })
        }
      }
    },
    handleTaskRemote(query) {
      if (query !== '') {
        let param = { taskName: query };
        if (this.organizationType === 3) {
          param.tslId = this.queryParams.tslId
        }
        this.taskLoading = true
        listTask(param).then(response => {
          this.taskOptions = response.rows
          this.taskLoading = false
        }).catch(() => {
          this.taskLoading = false
        })
      }
    },
    formattedTotal(amount) {
      const formatter = new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })

      return formatter.format(amount)
    },
    handleCheckAndAccept(val){
      this.$confirm('确定要验收该发票吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.status = val
        toExamine(this.form).then(res=>{
          this.toExamineOpen = false
          this.invoiceOpen = false
          this.getList()
        })
      }).catch(() => {})

    },
  },
  filters: {
    invoiceTypeName(value) {
      switch (value) {
        case 1: return '专票';
        case 2: return '普票';
        default: return '';
      }
    }
  },
  watch:{
    detailPayslipData:{
      handler(val){
        if (val){
          this.queryParams.taskNo = val.taskNo
          this.getList()
        }
      },
      immediate:true
    }
  }
};
</script>
<style lang="scss" scoped>
.invoiceTaskQueryClass{
  margin-top: 20px;
}
::v-deep .el-drawer__body{
  margin: 10px;
}
.dialog-footer{
  left: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  height: 55px;
  padding: 10px 20px;
  position: absolute;
  justify-content: flex-end;
  background-color: #ffffff;
  box-shadow: 1px 2px 4px rgba(0, 21, 41, 0.35);
}
</style>
